<template>
  <!-- ActivityDetails 活动详情 -->
  <view class="container" style="position: relative">
    <Header title="活动详情" v-model:model-value="headerHeight" :isBoxShadow="false"></Header>
    <view
      style="position: fixed; left: 0; z-index: 997; width: 100%"
      :style="{
        opacity: `${tabOpacity}`,
        top: tabOpacity ? headerHeight + 'px' : '-500px',
      }"
    >
      <Tabs v-model="currentTab" background-color="#FFF" :is-scroll-top="false">
        <TabNav tabBarColor="#2878FF" @on-item="handleOnItem" />
        <template v-for="(item, index) in tabsData" :key="index">
          <TabsItem v-if="item.isShow" :name="item.title" :value="item.id"></TabsItem>
        </template>
      </Tabs>
    </view>
    <view
      id="banner-position"
      style="position: absolute; left: 0"
      :style="{ top: -rpx250 + 'px' }"
    ></view>

    <Banner id="banner" :banner-url="data?.coverUrl" :end-time="data?.enrollEndTime"></Banner>
    <view class="info-conatiner">
      <BasicInformation
        id="basicInformation"
        :title="data?.title"
        :registrations-number="data?.passedNum"
        :address-name="data?.addressName"
        :address="data?.address"
        :longitude="String(data?.longitude)"
        :latitude="String(data?.latitude)"
        :start-time="data?.startTime"
        :end-time="data?.endTime"
        :register-id="data?.register?.id"
        :approval-status="data?.register?.approvalStatus"
        :start-price="data?.startPrice"
        :original-price="data?.originalPrice"
        :tag-name="data?.tagName"
        :start-flag="data?.startFlag"
        :pay-ticket="data?.payTicket"
      ></BasicInformation>

      <RegisteredPersonnels
        v-if="type === 'register'"
        id="registeredPersonnels"
        :personnelList="personnelList"
        :registrations-number="data?.passedNum"
        :oprationText="oprationText"
        :openRegNum="data?.openRegNum"
        :remaining-seats="data?.maxNum"
        :enroll-restrict="data?.enrollRestrict"
        @to-all="toApplicantsList"
      ></RegisteredPersonnels>

      <Invutation
        v-if="type === 'register'"
        id="invutation"
        :openInviteStatus="data?.openInviteStatus"
        :inviteRegisterNum="data?.inviteRegisterNum"
        :activityId="data?.id"
      ></Invutation>

      <OrganizingUnit
        id="organizingUnit"
        v-if="organizingUnitList.length"
        :organizingUnitList="organizingUnitList"
      ></OrganizingUnit>

      <view
        v-for="(item, index) in richTextData"
        style="position: relative"
        :key="index"
        :id="item.id"
      >
        <view
          :id="item.id + '-position'"
          style="position: absolute; left: 0"
          :style="{ top: -rpx250 + 'px' }"
        ></view>
        <Crad :title="item.title">
          <TRichText :content="item.content" />
        </Crad>
      </view>
    </view>
    <ContractConnectionModal
      v-if="data?.displayRegister"
      :activityId="data?.id"
    ></ContractConnectionModal>
  </view>
</template>

<script lang="ts" setup>
  /**  ActivityDetails  活动详情 */
  import Header from '@/components/Header/index.vue';
  import { type PropType } from 'vue';
  import TRichText from '@/components/TRichText/index.vue';

  import Banner from './Banner.vue';
  import BasicInformation from './BasicInformation.vue';
  import RegisteredPersonnels from './RegisteredPersonnels.vue';
  import OrganizingUnit from './OrganizingUnit.vue';
  import Invutation from './Invutation.vue';
  import Crad from '@/components/Crad/index.vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import { ref, getCurrentInstance, watch, computed } from 'vue';
  import type {
    IActivityListResData,
    IOrganizingUnit,
    IPrticipantsListResData,
  } from '@/api/activity/types';
  import { onPageScroll } from '@dcloudio/uni-app';
  import { useThrottleFn } from '@vueuse/core';
  import { isLogin } from '@/utils/is';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { navigateTo } from '@/router';
  import type { IRichTextData } from '../types';
  import ContractConnectionModal from './ContractConnectionModal.vue';

  const props = defineProps({
    activityListResData: {
      type: Object as PropType<IActivityListResData>,
      default: null,
    },
    type: {
      type: String as PropType<'preview' | 'register'>,
      default: 'preview',
    },
    personnelList: {
      type: Array as PropType<IPrticipantsListResData[]>,
      default: () => [],
    },
    organizingUnitList: {
      type: Array as PropType<IOrganizingUnit[]>,
      default: () => [],
    },
    richTextData: {
      type: Array as PropType<IRichTextData[]>,
      default: () => [],
    },
  });
  const emtis = defineEmits(['pageScrollTo']);
  const ins: any = getCurrentInstance();
  const headerHeight = ref(0);

  const tabsHeight = uni.upx2px(76);

  /**header 高度 +tabs高度*/
  const excessHeight = computed(() => {
    return headerHeight.value + tabsHeight;
  });

  const rpx250 = uni.upx2px(250);

  /** 详情数据 */
  const data = ref<IActivityListResData>();

  watch(
    () => props.activityListResData,
    (val) => {
      if (val) {
        data.value = val;
      }
    },
  );

  /**tabs 数据 */

  const initTabsData = [
    {
      title: '基础信息',
      id: 'banner',
      top: 0,
      height: 0,
      isShow: true,
    },
    {
      title: '地址信息',
      id: 'basicInformation',
      top: 0,
      height: 0,
      isShow: false,
    },
    {
      title: '已报名人员',
      id: 'registeredPersonnels',
      top: 0,
      height: 0,
      isShow: false,
    },
    {
      title: '',
      id: 'invutation',
      top: 0,
      height: 0,
      isShow: false,
    },
    {
      title: '举办单位',
      id: 'organizingUnit',
      top: 0,
      height: 0,
      isShow: false,
    },
  ];

  const tabsData = ref([...initTabsData]);

  /**富文本列表 */

  watch(
    () => props.richTextData,
    (val) => {
      tabsData.value = [];
      tabsData.value.push(...initTabsData, ...val);
    },
    { deep: true },
  );

  const currentTab = ref(tabsData.value[0].id);

  // 初始化高度和距离顶部高度
  const initTabsTop = () => {
    return new Promise((resolve, reject) => {
      const query = uni.createSelectorQuery().in(ins);
      tabsData.value.forEach((item, index) => {
        query
          .select(`#${item.id}`)
          .boundingClientRect((data: any) => {
            if (!data) return;
            item.height = data.height;
            item.top = data.top - excessHeight.value;
            if (index == tabsData.value.length - 1) {
              resolve('');
            }
          })
          .exec();
      });
    });
  };

  const tabOpacity = ref(0);

  /** 是否关闭滚动切换tab */
  let openScroll = true;
  onPageScroll((res) => {
    tabOpacity.value = res.scrollTop * 0.05;
  });

  // 滚动页面，自动切换tab
  onPageScroll(
    useThrottleFn(async (res) => {
      if (!openScroll) return;
      await initTabsTop();
      /**基础信息总体高度 */
      const basicInfoHeight = tabsData.value.slice(0, 5).reduce((pre, cur, index) => {
        // 预览不计算高度的模块
        if (
          props.type === 'preview' &&
          (tabsData.value[index].id === 'registeredPersonnels' ||
            tabsData.value[index].id === 'invutation')
        ) {
          return pre;
        }
        return pre + cur.height;
      }, 0);

      if (res.scrollTop + excessHeight.value <= basicInfoHeight) {
        currentTab.value = tabsData.value[0].id;
        return;
      }

      tabsData.value.forEach((item, index) => {
        if (
          item.top <= 0 &&
          item.height < Math.abs(item.top) + excessHeight.value &&
          index != tabsData.value.length - 1
        ) {
          currentTab.value = tabsData.value[index + 1].id;
        }
      });
    }, 100),
  );

  // 点击tab切换加滚动

  const handleOnItem = (item: any) => {
    openScroll = false;
    emtis('pageScrollTo', '.container >>> #' + item.value + '-position', () => {
      setTimeout(() => {
        openScroll = true;
      }, 1500);
    });
  };

  /**报名人员 */

  const oprationText = computed(() => {
    return data.value?.displayRegister ? '查看活动人脉' : '';
  });

  const useUser = useUserStoreWithOut();
  function toApplicantsList() {
    isLogin(() => {
      if (data.value?.displayRegister) {
        navigateTo({
          name: 'connectionSquare',
          options: { activityId: data.value!.id! },
        });
      }
    });
  }

  const toaAtivityDetailInvitationRanking = () => {
    navigateTo({
      name: 'activityDetailInvitationRanking',
      options: {
        activityId: data.value?.id!,
      },
    });
  };
</script>
<style lang="scss" scoped>
  .container {
    .info-conatiner {
      padding: 0 24rpx;
      position: relative;
      top: -48rpx;
      display: flex;
      flex-direction: column;
      gap: 24rpx;
      padding-bottom: calc(constant(safe-area-inset-bottom) + 140rpx);
      padding-bottom: calc(env(safe-area-inset-bottom) + 140rpx);
    }
  }
</style>
